package com.zxc.project.base;

import lombok.Data;
import org.springframework.util.Assert;
import com.zxc.project.exception.GlobalExceptionEnum;

import java.util.Optional;

/**
* @author zxc_user
* @date 2021/3/3 20:49
* @version 1.0
* @description 基础通用返回对象
**/
@Data
public class BaseResponseEntity<T> {

    //code值
    private Integer code;

    //信息
    private String msg;

    //数据
    private T data;

    public static  <T> BaseResponseEntity<T> success(T data) {
        BaseResponseEntity<T> baseResponseEntity = new BaseResponseEntity<>();
        baseResponseEntity.setData(data);
        baseResponseEntity.setInfo(GlobalExceptionEnum.SUCCESS);
        return baseResponseEntity;
    }

    public static <T> BaseResponseEntity<T> fail(BaseException baseException) {
        return fail(null, baseException);
    }

    public static <T> BaseResponseEntity<T> fail(T data) {
        return fail(data, null);
    }

    public static <T> BaseResponseEntity<T> fail(T data, BaseException baseException) {
        BaseResponseEntity<T> baseResponseEntity = new BaseResponseEntity<>();
        baseResponseEntity.setData(data);
        baseResponseEntity.setInfo(Optional.ofNullable(baseException).orElse(GlobalExceptionEnum.FAIL));
        return baseResponseEntity;
    }

    public void setInfo(BaseException baseException) {
        Assert.notNull(baseException, "baseException不能为空");
        this.setCode(baseException.getCode());
        this.setMsg(baseException.getMsg());
    }
}
